package com.forum.service;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.forum.bean.ArticleAudits;
import com.forum.common.Result;
import com.forum.dto.ArticleAuditRequest;
import com.forum.bean.Articles;
import com.forum.dto.ArticleListDto;
import com.forum.dto.AuditRecordDto;
import com.forum.mapper.ArticleAuditMapper;
import com.forum.mapper.ArticlesMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class ArticleAuditService {

    @Autowired
    private ArticlesMapper articleMapper;

    @Autowired
    private ArticleAuditMapper articleAuditMapper;

    /**
     * 文章审核接口：根据审核结果更新文章状态
     * @param req 文章审核请求参数，包括文章ID、审核结果和审核意见
     * @return 统一返回结果，审核成功或失败信息
     */
    @Transactional
    public Result<String> auditArticle(ArticleAuditRequest req) {
        try {
            if (req.getArticleId() == null || req.getApproved() == null) {
                return Result.fail("参数不完整");
            }
            // 根据文章ID查询文章记录
            Articles article = articleMapper.selectById(req.getArticleId());
            if (article == null) {
                return Result.fail("文章不存在");
            }
            // 只允许对状态为待审核（1）的文章进行审核
            if (!article.getStatus().equals(1)) {
                return Result.fail("文章已审核，无法重复审核");
            }

            // 根据审核结果更新状态：审核通过设置为2，不通过设置为0
            if (req.getApproved()) {
                article.setStatus(2);
            } else {
                article.setStatus(3);
            }

            ArticleAudits audits = new ArticleAudits();
            audits.setArticleId(req.getArticleId());
            audits.setStatus(article.getStatus());
            audits.setReason(req.getComment());
            audits.setCreatedAt(LocalDateTime.now());
            articleAuditMapper.insert(audits);

            // 可以在此处记录审核意见，例如记录到日志或更新审核记录表（若有）

            int rows = articleMapper.updateById(article);
            if (rows != 1) {
                return Result.fail("文章审核更新失败");
            }
            return Result.ok("文章审核成功");
        } catch (Exception e) {
            return Result.fail("审核异常：" + e.getMessage());
        }
    }


    /**
     * 分页获取审核记录列表
     */
    public Result<IPage<AuditRecordDto>> getAuditRecordList(int pageNum, int pageSize,String searchKey) {
        try {
            Page<AuditRecordDto> page = new Page<>(pageNum, pageSize);
            IPage<AuditRecordDto> pageData = articleAuditMapper.selectAuditRecordList(page,searchKey);
            return Result.ok(pageData);
        } catch (Exception e) {
            return Result.fail("查询审核记录异常：" + e.getMessage());
        }
    }

}
